package uvt.gui.mainframe.subpanel.addsss;

import java.awt.Color;

import javax.swing.JButton;

import org.openstreetmap.gui.jmapviewer.Coordinate;

import uvt.database.Database;
import uvt.database.InsertOperations;
import uvt.gui.mainframe.object.InfoFrame;
import uvt.gui.mainframe.object.command.Command;
import uvt.map.PositionsSettings;
import uvt.map.graph.element.Segment;
import uvt.map.mapmarker.MapPolygonImpl;

public class AddSegmentButton extends JButton implements Command {
	
	private Validable validate;
	private TextFieldGetter getter;
	
	public AddSegmentButton(Validable validate,TextFieldGetter getter) {
		super("Add Segment");
		this.validate = validate;
		this.getter = getter;
	}
	
	public void execute() {
		try {
			validate.validateForAddSegmentButton();
			Coordinate firstCoord = CoordinateResources.getInstance().getSegmentStart();
			CoordinateResources.getInstance().setSegmentStart(new Coordinate(Double.valueOf(getter.getLatitude()),
                                                                             Double.valueOf(getter.getLongitude())));
			CoordinateResources.getInstance().addSegmetInList(new Segment(firstCoord.getLat(),
														                  firstCoord.getLon(),
														                  Double.valueOf(getter.getLatitude()),
														                  Double.valueOf(getter.getLongitude())));
			((InsertOperations)Database.getInstace()).insertRowStreetSegment(String.valueOf(firstCoord.getLat()), 
					                                                         String.valueOf(firstCoord.getLon()),
					                                                         getter.getLatitude(),
					                                                         getter.getLongitude());
			MapPolygonImpl.setPolygonColor(Color.yellow);
			PositionsSettings.getInstance().addSegmentOnMap("",new Segment(firstCoord.getLat(),
					                                                       firstCoord.getLon(),
					                                                       Double.valueOf(getter.getLatitude()),
					                                                       Double.valueOf(getter.getLongitude())));
			Thread t = new Thread(new Runnable() {
				public void run() {
					new InfoFrame("Information","Segment was added in database!");
			    }
			});
			t.start();
		} catch(final Exception ex) {
			Thread t = new Thread(new Runnable() {
				public void run() {
					new InfoFrame("Error",ex.getMessage());
				}
			});
			t.start();
		}
		
	}
	
}